import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/login.vue'
import Layout from '../views/layout/layout.vue'
import Article from '../views/articles/article.vue'
import Home from '../views/home/home.vue'
import Edit from '../views/articles/edit.vue'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      children: [{
        path: '', // 为‘’时候默认会显示这个组件
        component: Home
      },
      { path: '/home', component: Home },
      { path: '/article', component: Article },
      { path: '/edit/:id', component: Edit }
      ]
    }
  ]
})
// 添加路由守卫功能
const master = ['/', '/article']
router.beforeEach((to, from, next) => {
  const extStr = localStorage.getItem('myStr')
  // 数组.includes（东西）:如果数组包含东西，返回true
  if (master.includes(to.path) && !extStr) {
    // console.log('啥也不是')
    next('/login')
  } else if (to.path === '/login' && extStr) {
    next('/') // 如果有密码不能到登录页
  } else {
    next()
  }
})
export default router
